<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div style="width: 100%; display: flex; flex-direction: column; height: 100vh;">
    <div style="display: flex; align-items: center; padding: 1px 15px;  position: relative;">
      <!-- 左侧新建按钮 -->
      <el-button class="idoo-details-add">新建</el-button>
      <!-- 右侧信息区域：垂直展示 -->
      <div style="display: flex; flex-direction: column; margin-left: 10px;">
        <span style="font-size: 15px;"> <el-button type="primary" link @click="handleBack">产品</el-button></span>
        <div style="display: flex; align-items: center; font-size: 14px; margin-top: 4px;">
          <span class="sub-title">{{ detailsTitle }}</span>
          <el-tooltip content="保存" placement="top" v-if="isFormChanged">
            <el-icon class="hover-icon" style="margin-left: 10px;" @click="handleSave">
              <UploadFilled />
            </el-icon>
          </el-tooltip>
          <el-tooltip content="撤销修改" placement="top" v-if="isFormChanged">
            <el-icon class="hover-icon" style="margin-left: 10px;" @click="handleRevert">
              <RefreshLeft />
            </el-icon>
          </el-tooltip>
        </div>
      </div>
    </div>
    <!-- 带阴影的分割线 -->
    <div class="divider"></div>
    <!-- 后续内容区域：背景色为淡灰色，填满剩余区域 -->
    <div class="content-section">
      <div style="display: flex; width: 100%; ">

        <!-- 左侧：无阴影的Card，占整体宽度的65%，用于表单的详情数据 -->
        <div style="height: auto; width: 65%; margin-right: 10px;">
          <el-card style="box-shadow: none;">
            <el-form :model="productForm" style="width: 100%;">
              <el-row>
                <el-col :span="18">
                  <el-form-item prop="productName">
                    <el-input v-model="productForm.productName"
                              style="font-size: 30px; height: 60px; line-height: 60px; width: 100%; padding: 10px;"
                              class="idoo-details-input" placeholder="例如：低压6级模锻动叶片毛坯"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-upload style="float: right; margin-right: 20px;" class="avatar-uploader" :show-file-list="false"
                             :on-change="handleFileChanged">
                    <img v-if="productForm.productPic" :src="productForm.productPic" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                      <Plus />
                    </el-icon>
                    <template #file="{ file }">
                      <div>
                        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                        <span class="el-upload-list__item-actions">
                          <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                            <el-icon>
                              <ZoomIn />
                            </el-icon>
                          </span>
                          <span v-if="productForm.productPic" class="el-upload-list__item-delete"
                                @click="handleRemoves(file)">
                            <el-icon>
                              <Delete />
                            </el-icon>
                          </span>
                        </span>
                      </div>
                    </template>
                  </el-upload>
                </el-col>
              </el-row>
              <el-row style="margin-bottom: 25px; margin-left: 25px;">
                <el-col :span="24">
                  <el-checkbox-group v-model="checkList">
                    <el-checkbox @change="typeChange" label="销售" />
                    <el-checkbox @change="typeChange" label="采购" />
                    <el-checkbox @change="typeChange" label="生产" />
                    <el-checkbox @change="typeChange" label="库存计划" />
                  </el-checkbox-group>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="产品信息">
                    <el-radio-group v-model="productForm.productInfo">
                      <el-radio :label="'实物'">实物</el-radio>
                      <el-radio :label="'服务'">服务</el-radio>
                      <el-radio :label="'组合'">组合</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="产品种类">
                    <el-select v-model="productForm.productCategory" placeholder="请选择产品种类" style="width: 70%;"
                               class="idoo-details-select">
                      <el-option v-for="item in codeStore().getSystemCode('PRODUCT_CATEGORY') as CodeValueType[]"
                                 :key="item.bizValue" :label="item.bizName" :value="item.bizValue" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="开票规则">
                    <el-select v-model="productForm.productInvoicing" placeholder="请选择产品种类" style="width: 70%;"
                               class="idoo-details-select">
                      <el-option v-for="item in codeStore().getSystemCode('PRODUCT_INVOICING_RULE') as CodeValueType[]"
                                 :key="item.bizValue" :label="item.bizName" :value="item.bizValue" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                </el-col>
              </el-row>
              <el-row :gutter="20" v-if="checkList.indexOf('销售') != -1">
                <el-col :span="12">
                  <el-form-item label="销售价格">
                    ￥<el-input v-model="productForm.productSailPrice" style="width: 50%;" class="idoo-details-input"
                               placeholder="0.00 "></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="销售税">
                    <el-select clearable v-model="productForm.productSailTax" placeholder="请选择税比例" style="width: 70%;"
                               class="idoo-details-select">
                      <el-option v-for="item in codeStore().getSystemCode('PRODUCT_SAIL_TAX') as CodeValueType[]"
                                 :key="item.bizValue" :label="item.bizName" :value="item.bizValue" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20" v-if="checkList.indexOf('采购') != -1">
                <el-col :span="12">
                  <el-form-item label="采购价格">
                    ￥<el-input v-model="productForm.productPurchasePrice" style="width: 50%;" class="idoo-details-input"
                               placeholder="0.00 "></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="采购税">
                    <el-select clearable v-model="productForm.productPurchaseTax" placeholder="请选择税比例" style="width: 70%;"
                               class="idoo-details-select">
                      <el-option v-for="item in codeStore().getSystemCode('PRODUCT_SAIL_TAX') as CodeValueType[]"
                                 :key="item.bizValue" :label="item.bizName" :value="item.bizValue" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="成本">
                    <el-input v-model="productForm.productPrice" style="width: 100%;" class="idoo-details-input"
                              placeholder="例如：浙江省杭州市滨江区网商路699号1号楼5楼"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="计量单位">
                    <el-input v-model="productForm.productUnit" style="width: 100%;" class="idoo-details-input"
                              placeholder="例如：https://www.alibaba.com/"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20" style="margin-top: 20px;">
                <!-- 将标签页移到这里，表单下方 -->
                <el-tabs type="border-card" v-model="activeName" class="demo-tabs" @tab-click="tabHandleClick"
                         style="overflow-y: auto;">
                  <el-tab-pane v-if="checkList.indexOf('销售') != -1" label="销售" name="销售">
                    <productSalesInfo />
                  </el-tab-pane>
                  <el-tab-pane v-if="checkList.indexOf('采购') != -1" label="采购" name="采购">Config</el-tab-pane>
                  <el-tab-pane v-if="checkList.indexOf('生产') != -1" label="生产" name="生产">Config</el-tab-pane>
                  <el-tab-pane v-if="checkList.indexOf('库存计划') != -1" label="库存" name="库存">Config</el-tab-pane>
                </el-tabs>
              </el-row>
            </el-form>
          </el-card>
        </div>

        <!-- 右侧：修改记录区域，保持背景色 -->
        <div style="width: 35%; padding: 5px; overflow-y: auto;" v-if="formId">
          <!-- 按钮行 -->
          <div style="display: flex;margin-bottom: 10px;">
            <el-button :icon="Edit" :class="recordRemark ? 'idoo-details-add' : 'el-button-primary'"
                       :type="recordRemark ? 'primary' : ''" @click="recordRemarkChoose"></el-button>
            <el-button :icon="Search" :class="recordSearch ? 'idoo-details-add' : 'el-button-primary'"
                       :type="recordSearch ? 'primary' : ''" @click="recordSearchChoose"></el-button>

            <el-input ref="searchRef" v-if="recordSearch" v-model="recordSearchInfo" placeholder="搜索：操作记录内容：操作人/字段名称/内容"
                      style="margin-left: 50px;width:60%">
              <template #append>
                <el-button :icon="Search" @click="recordSearching" style="display:inherit !important;" />
              </template>
            </el-input>
          </div>
          <div v-if="recordRemark">
            <el-input type="textarea" v-model="recordRemarkInfo" class="record-remark-textarea"
                      placeholder="记录详情内部说明..." style="width: 70%;"></el-input>
          </div>
          <div style="margin-top: 5px;" v-if="recordRemark">
            <el-button type="primary" @click="sendRecordRemark" size="large"
                       style="width: 60px; height: 35px; font-size: small;">发送</el-button>
          </div>
          <!-- 操作记录组件 -->
          <ProductRecord :recordInfos="recordInfos" />
        </div>


        <el-dialog v-model="dialogVisible">
          <img w-full :src="productForm.productPic" alt="Preview Image" />
        </el-dialog>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref, watch, nextTick } from 'vue';
import { useRoute } from 'vue-router';
import { UploadFilled, RefreshLeft, Edit, Search, Plus, ZoomIn, Delete } from '@element-plus/icons-vue';
import router from '@/router';
import { ElMessage, ElMessageBox, type TabsPaneContext } from 'element-plus';
import { codeStore } from '@/stores/codeStore';
import {
  _getProductInfo, _getRecordInfos, _modifyProductInfo, _saveProductInfo,
  _saveRecordRemarkInfos, _searchRecordRemarkInfos
} from '@/api/generic/product/product-api';
import type { ProductForm } from '@/types/product/types';
import type { CodeValueType } from '@/types/piniatypes';
import { getChangedFields, updateWrapperBuilder } from '@/utils/form/updateFormHelper';
import type { BaseRecordVo } from '@/types/basetypes';
import ProductRecord from '@/components/base/record/IdooRecord.vue';
import productSalesInfo from './product-sales-info.vue';
import type { UploadProps } from 'element-plus/lib/components/index.js';
const route = useRoute();
//详情页标题
const detailsTitle = ref("");
//判断主表单是否变化
const isFormChanged = ref(false);
//路由参数
let formId = route.query.id || "";
//操作记录数据
const recordInfos = ref<BaseRecordVo[]>([]);
//操作记录-备注点击
const recordRemark = ref(false);
//操作记录-备注输入框
const recordRemarkInfo = ref("");
//操作记录-搜索点击
const recordSearch = ref(false);
//操作记录-搜索输入框
const recordSearchInfo = ref("");
//操作记录-搜索输入框ref
const searchRef = ref(null);
//产品种类
const checkList = ref<string[]>(["销售"]);
//tabs初始加载
const activeName = ref('销售')
//图片查看
const dialogVisible = ref(false)

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const handleRemoves = (uploadFile: any) => {
  console.log(uploadFile)
}

const handlePictureCardPreview: UploadProps['onPreview'] = () => {
  dialogVisible.value = true
}

//切换子组件
const tabHandleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event)
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const handleFileChanged = (file: any) => {
  console.log(file);
  const isImage = file.raw.type.startsWith('image/');
  const isLt2M = file.raw.size / 1024 / 1024 < 2;
  console.log(file.raw.size);
  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return;
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!');
    return;
  }

  // 立即显示预览
  const reader = new FileReader();
  reader.onload = (e) => {
    if (e.target && e.target.result) {
      productForm.value.productPic = e.target.result as string;
    }
  };
  console.log(productForm.value.productPic)
  reader.readAsDataURL(file.raw);
}

const typeChange = () => {
  console.log(checkList.value)
  if (checkList.value) {
    if (checkList.value.indexOf("销售") != -1) {
      activeName.value = '销售'
    }
    else if (checkList.value.indexOf("采购") != -1) {
      activeName.value = '采购'
    }
    else if (checkList.value.indexOf("生产") != -1) {
      activeName.value = '生产'
    }
    else if (checkList.value.indexOf("库存计划") != -1) {
      activeName.value = '库存'
    }
  }
  productForm.value.productType = checkList.value.join(",") || "";
}


// 初始化表单数据
const productForm = ref<ProductForm>({
  id: '',
  /**租户编号*/
  tenantId: '',
  /**部门ID；空则为公共客户数据*/
  deptId: '',
  /**产品名称*/
  productName: '',
  /**产品编号*/
  productCode: '',
  /**产品图片*/
  productPic: '',
  /**产品类型（销售、采购、生产）*/
  productType: '',
  /**产品信息（实物、服务、组合）*/
  productInfo: '',
  /**产品种类（成品、半成品、原材料）*/
  productCategory: '',
  /**开票规则*/
  productInvoicing: '',
  /**销售价格*/
  productSailPrice: 0.00,
  /**销售税*/
  productSailTax: '',
  /**采购价格*/
  productPurchasePrice: 0.00,
  /**采购税*/
  productPurchaseTax: '',
  /**成本（如果存在bom可通过bom计算）*/
  productPrice: 0.00,
  /**库存数量*/
  productInventoryNum: 0,
  /**是否开启库存计划 1否 0是 (是的时候展示库存数量)*/
  productHasInventoryPlan: '',
  /**产品说明*/
  productDescribe: '',
  /**质保期（码表配置）*/
  productWarranty: '',
  /**计量单位*/
  productUnit: '',
  /**创建部门*/
  createDept: '',
})
const originalFormData = ref<ProductForm>({});
originalFormData.value = JSON.parse(JSON.stringify(productForm.value));
const recordRemarkChoose = () => {
  recordRemark.value = !recordRemark.value;
  if (recordRemark.value) {
    nextTick(() => {
      const textarea = document.querySelector('.el-textarea__inner') as HTMLTextAreaElement;
      textarea.focus();
    });
  }
}

const recordSearchChoose = () => {
  recordSearch.value = !recordSearch.value;
  if (recordSearch.value) {
    nextTick(() => {
      if (searchRef.value) {
        const a = searchRef.value as HTMLTextAreaElement;
        a.focus();
      }
    });
  }
}

const resetForm = () => {
  originalFormData.value = JSON.parse(JSON.stringify(productForm.value));
  detailsTitle.value = productForm.value.productName || '新建';
  isFormChanged.value = false;
}

// 监听表单变化
watch(() => productForm.value, (newVal) => {
  console.log(productForm.value);
  console.log(originalFormData.value)
  isFormChanged.value = JSON.stringify(newVal) !== JSON.stringify(originalFormData.value);
}, { deep: true });

//初始化加载数据
onMounted(async () => {
  console.log("onMounted", productForm.value)
  // originalFormData.value = JSON.parse(JSON.stringify(productForm.value));
  console.log(originalFormData.value)
  detailsTitle.value = '新建'
  //获取用户数据
  if (formId) {
    //编辑
    const res = await _getProductInfo({ id: formId.toString() });
    if (res.code === 200 && res.data) {
      productForm.value = res.data;
      checkList.value = res.data.productType?.split(",") || [];
      originalFormData.value = JSON.parse(JSON.stringify(res.data));
      detailsTitle.value = productForm.value.productName || '';
    }
    const rres = await _getRecordInfos({ id: formId.toString() });
    console.log(rres.code);
    if (rres.code === 200 && rres.data) {
      recordInfos.value = rres.data;
    }
  }
  console.log("onMounted", productForm.value)
});
//返回按钮
const handleBack = () => {
  if (isFormChanged.value) {
    ElMessageBox.confirm('是否保存当前数据？', '确认保存', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      await handleSave();
    }).catch(() => {
      router.push({ path: route.fullPath.replace('/add', '') })
    })
  } else {
    router.push({ path: route.fullPath.replace('/add', '') })
  }
}
//发送备注消息
const sendRecordRemark = async () => {
  if (formId && recordRemark.value) {
    await _saveRecordRemarkInfos({
      bizId: formId.toString(),
      remark: recordRemarkInfo.value.toString(),
    })
    //刷新操作记录
    const rres = await _getRecordInfos({ id: formId.toString() });
    if (rres.code === 200 && rres.data) {
      recordInfos.value = rres.data;
    }
    recordRemarkInfo.value = '';
  }
}
//搜索备注内容
const recordSearching = async () => {
  if (formId && recordSearch.value) {
    const ress = await _searchRecordRemarkInfos({
      _search_bizid: formId.toString(),
      _search_content: recordSearchInfo.value
    })
    if (ress.code === 200 && ress.data) {
      recordInfos.value = ress.data;
    }
  }
}
// 保存处理函数
const handleSave = async () => {
  //TODO 表单校验
  const formData = productForm.value
  try {
    formData.productType = checkList.value.join(',')
    const i = getChangedFields(originalFormData.value, formData)
    console.log(i);
    let res;
    if (formId) {
      const upWrap = updateWrapperBuilder(formData, i); // 传递 formData 作为参数
      res = await _modifyProductInfo(upWrap); // 使用 upWrap 作为参数
    } else {
      res = await _saveProductInfo(formData);
      if (res.code === 200 && res.data) {
        formId = res.data[0];
        console.error(formId)
        productForm.value.id = formId;
      }
    }
    if (res && res.code === 200) {
      resetForm();
      //刷新操作记录
      const rres = await _getRecordInfos({ id: formId.toString() });
      console.log(rres.code);
      if (rres.code === 200 && rres.data) {
        recordInfos.value = rres.data;
      }
    }
  } catch (error) {
    console.error('保存失败:', error);
  }
};

// 撤销修改，还原表单
const handleRevert = () => {
  productForm.value = JSON.parse(JSON.stringify(originalFormData.value));
};
</script>
<style scoped>
:deep(.el-input__inner) {
  --el-input-inner-height: none;
}

:deep(.el-card__body) {
  padding: 1% !important;
  justify-content: unset !important;
}

.hover-icon {
  cursor: pointer;
  transition: transform 0.2s ease;
}

.hover-icon:hover {
  transform: translateY(-2px);
}

.sub-title {
  font-size: 14px;
  color: #666;
}

.divider {
  width: 100%;
  height: 1px;
  background-color: #ccc;
  margin-top: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.content-section {
  flex: 1;
  width: 100%;
  padding: 15px;
  background-color: #f5f5f5;
  box-sizing: border-box;
  overflow-y: auto;
}

.demo-tabs>.el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.demo-tabs {
  position: relative;
  width: 100%;
  overflow-y: auto;
}

:deep(.el-tabs__nav-wrap::after) {
  position: absolute;
  content: '';
  width: 100%;
  height: 2px;
  background-color: var(--el-border-color-light);
  bottom: 0;
  left: 0;
  z-index: 1;
}

:deep(.el-tabs__nav.is-top) {
  margin-left: 10px
}

:deep(.el-tabs__header) {
  width: 100%;
  margin-bottom: 0;
}

:deep(.el-tabs__nav-wrap) {
  width: 100%;
}

.avatar-uploader .avatar {
  width: 90px;
  height: 90px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 90px;
  height: 90px;
  text-align: center;
}

.el-form-item__label {
  color: black !important;
}

.el-tabs--border-card>.el-tabs__header {
  background-color: white !important
}

.el-tabs--border-card {
  border: 0px;
}

.el-tabs--border-card>.el-tabs__header .el-tabs__item {
  margin-top: 0px;
}

.el-tabs--border-card>.el-tabs__header .el-tabs__item.is-active {
  border-top-color: #922575;
}
</style>
